const db = wx.cloud.database()
const app = getApp();
const _ = db.command;
Page({
  data: {
    nickName: '',
    passWord: '',
    loginLoading: false,
  },
  onChangeNickName: function (e) {
    this.setData({
      nickName: e.detail
    })
  },
  onChangePassWord: function (e) {
    this.setData({
      passWord: e.detail
    })
  },
  navigatorRegister(e) {
    wx.redirectTo({
      url: '/pages/register/index',
    });
  },
  onShow() {
    wx.hideHomeButton({
      success: function () {
        // console.log(1);
      },
      fail: function () {
        // console.log(2);
      },
      complete: function () {
        // console.log(3);
      }
    });
  },
  // 登录按钮
  onSubmit: function (e) {
    this.setData({
      loginLoading: true,
    })
    if (this.data.nickName == '') {
      wx.showToast({
        title: '请输入账号！',
        icon: 'none'
      })
      return
    }
    if (this.data.passWord == '') {
      wx.showToast({
        title: '请输入密码！',
        icon: 'none'
      })
      return
    }
    // 开始使用云开发数据库
    const {
      nickName,
      passWord
    } = this.data;
    db.collection('Management_user').where({
      nickName: _.eq(nickName),
      passWord: _.eq(passWord)
    }).get().then(res => {
      if (res.data.length === 1) {
        // localstorage
        // 用户角色 权限校验
        const userInfo = res.data[0];
        wx.setStorageSync('userInfo', JSON.stringify(userInfo));
        app.globalData.userInfo = userInfo;
        wx.redirectTo({
          url: '/pages/index/index'
        });
      } else {
        wx.showToast({
          title: '登录失败！',
          icon: 'error'
        })
      }
    })
    this.setData({
      loginLoading: false,
    })
  }
})